import axios from 'axios'
import { nanoid } from 'nanoid'
const Person = {
    namespaced: true,
    state: {
        userList: [],

    },
    getters: {
        firstName(state) {
            return state.userList[0]
        }
    },
    mutations: {
        MODIFY_INFORM(state, payload) {
            state.userList = payload
        },
        ADD_PERSON(state, payload) {
            state.userList = payload
        },
        DEL_PERSON(state, payload) {
            state.userList = payload
        }
    },
    actions: {
       
        async handleEdit(context, payload) {
            const isEdit = await context.dispatch('isShowEdit', payload.id)
            if (isEdit) {
                return
            }
            context.state.userList.forEach((item, index) => {
                if (item.id == payload.id) {
                    item.name = payload.name;
                    item.say = payload.say || context.state.userList[index].say
                }
            })
            context.commit('MODIFY_INFORM', context.state.userList)
        },
        isShowEdit(context, payload) {
            // actions的函数，返回的是Promise，使用的时候需要async/await
            let editstaus = false
            context.state.userList.forEach((item) => {
                if (item.id == payload) {
                    item.isEdit = !item.isEdit
                    editstaus = item.isEdit
                }
            })
            return editstaus
        },
        async addPerson(context, payload) {
            let { name, age } = payload
            if (name == '' || age == '') {
                return
            }
            const say = await context.dispatch('saying')
            const id = nanoid()
            const arr = [...context.state.userList, { ...payload, say, id }]
            context.commit('ADD_PERSON', arr)
        },
        saying() {
            return axios.get('https://api.uixsj.cn/hitokoto/get?type=social').then((info) => {
                return Promise.resolve(info.data);
            }).catch((error) => {
                console.log(error);
            })
        },
        delPersonRow(context, payload) {
            const filtersData = context.state.userList.filter((item) => {
                return item.id != payload
            })
            context.commit('DEL_PERSON', filtersData)
        }
    },
    modules: {}
}

export default Person